package com.systop.dao;

import com.systop.entity.Comment;
import com.systop.entity.Comment;
import com.systop.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

import static com.systop.util.JdbcUtil.getConnection;

public class CommentDao {

    private Connection conn = null;
    private PreparedStatement pstmt = null;
    private ResultSet rs = null;

    public ArrayList<Comment> findAllByMsgId(Integer mid){
        ArrayList<Comment> commentList = new ArrayList<Comment>();
        // 获取链接
        try {
            conn = JdbcUtil.getConnection();
            String sql ="select * from t_comment WHERE mid = ?";
            // 运行sql 代码
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,mid);
            // 执行代码,获取结果集
            rs = pstmt.executeQuery();
            while (rs.next()) {
                Comment comment = new Comment();
                int id = rs.getInt("id");
                String content = rs.getString("content");
                Date pushtime = rs.getDate("pushtime");
                Date createtime = rs.getDate("createtime");
                comment.setId(id);
                comment.setMid(mid);
                comment.setContent(content);
                comment.setPushTime(pushtime);
                comment.setCreateTime(createtime);
                commentList.add(comment);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JdbcUtil.close(conn, pstmt, rs);
        }

        return commentList;
    }
    
    public int add(Comment comment){
        int i = 0;
        // 获取链接
        try {
            conn = getConnection();
            String sql = "INSERT INTO t_comment(mid,content,pushtime,createtime)VALUES(?,?,?,?)";
            // 运行sql 代码
            pstmt = conn.prepareStatement(sql);
            // 传递参数
            pstmt.setInt(1, comment.getMid());
            pstmt.setString(2, comment.getContent());
            pstmt.setDate(3,new java.sql.Date(comment.getPushTime().getTime()));
            pstmt.setDate(4,new java.sql.Date(new Date().getTime()));
            // 执行代码,获取结果集
            i = pstmt.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JdbcUtil.close(conn, pstmt, rs);
        }
        return i;
    }
}
